package com.corex.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.AsyncTask;
import android.os.StrictMode;

public class WebServiceCalls extends AsyncTask{
	public static final int GET = 0;
	public static final int POST = 1;
	private int method;
	private String request;
	
	public int getMethod() {
		return method;
	}

	public void setMethod(int method) {
		this.method = method;
	}

	public String getRequest() {
		return request;
	}

	public void setRequest(String request) {
		this.request = request;
	}

	@Override
	protected Object doInBackground(Object... urls) {
		String serviceUrl = (String) urls[0];
		String responceString = callService(serviceUrl,this.method,this.request);
		return responceString;
	}
	
	public String callService(String serviceUrl){
		String responceString = callService(serviceUrl,this.method,this.request);
		return responceString; 
	}
	
	private String callService(String urlstr,int method,String requestJson){
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		String responceOutput = "";
		try{
		URL url = new URL(urlstr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/json");
		conn.setRequestProperty("Accept", "application/json");
		
		
		OutputStream os = conn.getOutputStream();
		os.write(requestJson.getBytes());
		os.flush();
		
		/*
		switch (method) {
		case WebServiceCalls.GET:
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");
			break;
			
		case WebServiceCalls.POST:
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Accept", "application/json");
			conn.setDoOutput(true);
			
			OutputStream os = conn.getOutputStream();
			os.write(requestJson.getBytes());
			os.flush();
			break;
			
		default:
			break;
		}
		
		*/
			if (conn.getResponseCode() != 200) {
				
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			} else {

				BufferedReader br = new BufferedReader(new InputStreamReader(
						(conn.getInputStream())));

				String output;
				while ((output = br.readLine()) != null) {

					responceOutput = responceOutput + output;
				}
			}
			conn.disconnect();
 
	  } catch (MalformedURLException e) {
		e.printStackTrace();
 	  } catch (IOException e) {
 		e.printStackTrace();
 	  }catch (Exception e) {
 		e.printStackTrace();
 	  }
		
	return responceOutput;	
 
	}
}
